import { defineStore } from "pinia";
import { userkey } from "./keys";

interface IUserKey {
  menus: IMenuModel[];
  username: string;
}
type menu = IMenuModel & { children: IMenuModel[] };

export const useUserKey = defineStore(userkey, {
  state(): IUserKey {
    return {
      menus: [],
      username: "",
    };
  },
  getters: {
    routes() {
      let menus: menu[] = [];
      // parentId为0的是一级菜单，放到menus数组
      menus = this.menus
        .filter((item) => {
          return item.parentId === 0;
        })
        .map((item) => {
          return {
            ...item,
            children: [],
          };
        });
      // 找二级菜单
      this.menus.forEach((sub) => {
        // 找到二级菜单，我的parentId等于一级的id就是这个一级就是我的上级
        const par = menus.find((par) => par.id === sub.parentId);
        if (par) {
          par.children.push(sub);
        }
      });
      return menus;
    },
    permission(): string[] {
      return this.menus.map((item) => item.name);
    },
  },
});
